#!/bin/bash

# Copyright 2014 Intel Corporation, All Rights Reserved.

# Licensed under the Apache License, Version 2.0 (the"License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#  http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.


set -o xtrace
service vsm-api stop
service vsm-scheduler stop
service vsm-conductor stop
service vsm-agent stop
service vsm-physical stop
TOPDIR=$(cd $(dirname "$0") && pwd)

function is_controller() {
    ip_list=`hostname -I`
    if [[ ! -e /etc/vsmdeploy/deployrc ]]; then
        echo 0
        return
    fi

    file=/etc/manifest/server.manifest
    for ip in $ip_list; do
        cnt=`cat /etc/vsmdeploy/deployrc | grep VSM_HOST | grep $ip | wc -l`
        if [[ $cnt -gt 0 ]]; then
            echo 1
            return
        fi
    done
    echo 0
}

function clean_controller() {
    service vsm-api stop
    service vsm-scheduler stop
    service vsm-conductor stop
    service vsm-agent stop
    service vsm-physical stop
    if [[ `is_controller` -gt 0 ]]; then
        echo "Clean over! you have to run vsm-controller again."
        echo "Begin to install controller. (y/n)?"
        vsm-controller
    fi
}

function _clean_agent() {
    pgrep ceph | xargs -i kill -9 {}
    # kill radosgw
    pgrep radosgw | xargs -i kill -9 {}
    rm -rf /etc/ceph/*

    file=/etc/manifest/server.manifest

    for n in `ls /var/lib/ceph/osd`; do
        umount /var/lib/ceph/osd/$n
    done

    rm -rf /var/lib/ceph/*

    rm -rf /var/lib/ceph/mon/*
    rm -rf /var/lib/ceph/mds/*
    rm -rf /var/log/vsm/*
    rm -rf /var/run/ceph/*
    cp -rf /usr/local/bin/tools/etc/vsm/* /etc/vsm/
    cp -rf /etc/vsm/vsm.conf.sample /etc/vsm/vsm.conf
    #service vsm-agent restart
    #service vsm-physical restart
    echo "-------------------------------------------------"
    echo "Step 1"
    echo "You have to change auth-key in server.manifest."
    echo "Copy the output of agent-token from controller side."
    echo "-------------------------------------------------"
    echo "Step 2"
    echo "Run vsm-node on storage node."
    exit 0
}

function clean_agent() {
    echo "Before you begin to clean agent."
    echo "Make sure you've clean controller."
    _clean_agent
}

if [[ `is_controller` -gt 0 ]]; then
    clean_controller
else
    clean_agent
fi

set +o xtrace

